class Solution {
    boolean[][] check;
    int m = 0;
    int n = 0;
    int ret = 0;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    public int numIslands(char[][] grid) {
        m = grid.length;
        n = grid[0].length;

        check = new boolean[m][n];

        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == '1' && check[i][j] == false){
                    check[i][j] = true;
                    ret++;
                    dfs(grid, i, j);
                }
            }
        }
        return ret;
    }
    public void dfs(char[][] grid, int i, int j){
        for(int k = 0; k < 4; k++){
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && grid[x][y] == '1'){
                check[x][y] = true;
                dfs(grid, x, y);
            }
        }
    }
}